/**
 * Created by Ding on 2016/4/8.
 * Copyright (c) 2016, auais.com All Rights Reserved.
 * File Name:
 * Package Name:
 * Date:2016/4/8 11:23
 */
const ObjectID = require('mongodb').ObjectID;
const mongo = require('mongodb');
const GridStore = require('mongodb').GridStore;
const fs = require("fs");
const path = require('path');
const Grid = require('gridfs-stream');
const Busboy = require('busboy');
const inspect = require('util').inspect;
const gm = require("gm");
module.exports = {
    open:false,
    description:'更新上传信息',
    handler: (req, res, next)=>{

        if(!req.query._id)
        {
            return res.reply({message:"修改资源出错"});
        }
        req.context=req.context||{};
        const userId=req.context.user||new ObjectID(0);
        const compress=req.query.compress;
        const versionNum = req.query.version||'';
        const gfs = Grid(req.mongo, mongo);

        gfs.remove({_id:req.query._id}, function (err) {
            if (err) return res.err.mongoError(err);

            const busboy = new Busboy({headers: req.headers});
            //第三方中间件接收上传
            req.pipe(busboy);
            busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
                var ext = path.extname(filename).toLowerCase();
                var filesize = 0;
                const id = new ObjectID();
                const writestream = gfs.createWriteStream({
                    _id: id,
                    mode: "w",
                    filename: filename,
                    content_type: mimetype
                });
                //file.pipe(writestream);
                console.log(mimetype);
                if (mimetype.indexOf("image/") != -1 && compress=="true") {
                    console.log("压缩中 ……");
                    gm(file).resize('640', '640').stream().pipe(writestream);
                } else {
                    file.pipe(writestream);
                }

                file.on('end', function () {
                    //console.log("end");
                    const url = "http://" + req.headers.host + "/res/" + id+"/content";
                    const fileObj = {
                        id: id,
                        filename: filename,
                        content_type: mimetype,
                        filesize: filesize,
                        url: url
                    };
                    res.json(fileObj);

                }).on('error', function (err) {
                    console.log("err:" + err)
                }).on('data', function (data) {
                    filesize += data.length;
                    //   console.log(filesize);
                });

            })

        });

    }
};